package com.good.app.net

import android.text.TextUtils
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

class TokenInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()

        var tokenOld = SessionManager.instance!!.getToken()
        if (TextUtils.isEmpty(tokenOld)) {
            tokenOld = ""
        }
        val newRequest = request.newBuilder()
            .addHeader("token", tokenOld)
            .method(request.method(), request.body())
            .build()

        val response = chain.proceed(newRequest)

        val token = response.header("token")
        if (!TextUtils.isEmpty(token)) {
            SessionManager.instance!!.setToken(token.toString())
        }
        return response
    }
}